<?php

namespace app\lib\exception;

use \Exception;
use think\exception\Handle;
use think\Log;

class ExceptionHandle extends Handle{

    public $msg;
    public $code;
    public $errCode;

    /* 重写异常捕获方法 */
    public function render(Exception $e)
    {
        if($e instanceof BaseException){
            
            $this->msg = $e->msg;
            $this->code = $e->code;
            $this->errCode = $e->errCode;

        }else{

            if(config('app_debug')){
                return parent::render($e);
            }
            $this->msg = '服务器内部错误';
            $this->code = 500;
            $this->errCode = 999;
            
            $this->recordErrorLog($e);
        }

        $result = [
            'msg' => $this->msg,
            'request_url' => request()->url(),
            'errCode' => $this->errCode,
        ];
        
        return json($result,$this->code);
    
    }

    /* 记录错误日志 */
    public function recordErrorLog(Exception $e)
    {
        Log::init([
            'type' => 'File',
            'level' => ['error'],
        ]);
        Log::record($e->getMessage(),'error');
    }

}